﻿using EmbeddedSharp.Core;
using EmbeddedSharp.Scripting;
using EmbeddedSharp.Scripting.Function;

namespace Zove.Runtime.Core {
    /// <summary>
    /// Zoom function manager
    /// </summary>
    public class ZoomFunctionManager : ContextFunctionManager {

        public ILanguageNature LanguageNature { get; private set; }

        /// <summary>
        /// Default constructor
        /// </summary>
        public ZoomFunctionManager(ILanguageNature languageNature)
        {
            LanguageNature = languageNature;
        }

        /// <summary>
        /// Constructor with context
        /// </summary>
        /// <param name="context">the context</param>
        /// <param name="languageNature">the language nature</param>
        public ZoomFunctionManager(IContext context, ILanguageNature languageNature)
            : base(context)
        {
            LanguageNature = languageNature;
        }

        /// <summary>
        /// Get function by name
        /// </summary>
        /// <param name="functionName">the function name</param>
        /// <returns>the function node</returns>
        public override FuncNode GetFunction(string functionName) {
            FuncNode fn = base.GetFunction(functionName);

            if (fn == null) {
                int index = functionName.IndexOf('.');
                if (index > 0) {
                    string className = functionName.Substring(0, index);
                    ZoomClass zvc
                        = LanguageNature.ClassLoader.LoadByClassName(className);
                    UserDefinedFunctionNode udfNode = zvc.Functions[functionName];
                    fn = udfNode.Clone() as UserDefinedFunctionNode; // zvc.Functions[functionName];
                }
            }

            return fn;
        }
    }
}